import { useState, useEffect } from 'react';

export interface User {
  id: number;
  username: string;
  full_name: string;
  role_code: string;
  role_name: string;
}

export interface Permissions {
  canEditAll: boolean;
  canManageUsers: boolean;
  canManageRoles: boolean;
  dataSourceAccess: string[];
  hasDataSourceAccess?: boolean;
  editableFields?: string[];
}

export interface AuthState {
  user: User | null;
  permissions: Permissions | null;
  loading: boolean;
  error: string | null;
}

export function useAuth(tableName?: string, dataSource?: string) {
  const [state, setState] = useState<AuthState>({
    user: null,
    permissions: null,
    loading: true,
    error: null
  });

  useEffect(() => {
    checkAuth();
  }, [tableName, dataSource]);

  const checkAuth = async () => {
    try {
      setState(prev => ({ ...prev, loading: true, error: null }));

      // 构建查询参数
      const params = new URLSearchParams();
      if (tableName) params.append('tableName', tableName);
      if (dataSource) params.append('dataSource', dataSource);

      const response = await fetch(`/api/auth/permissions?${params.toString()}`);
      const data = await response.json();

      if (data.success) {
        setState({
          user: data.data.user,
          permissions: data.data.permissions,
          loading: false,
          error: null
        });
      } else {
        setState({
          user: null,
          permissions: null,
          loading: false,
          error: data.error || '获取用户信息失败'
        });
      }
    } catch (error) {
      console.error('检查认证状态失败:', error);
      setState({
        user: null,
        permissions: null,
        loading: false,
        error: '网络错误'
      });
    }
  };

  const login = async (username: string, password: string) => {
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password }),
      });

      const data = await response.json();
      
      if (data.success) {
        await checkAuth(); // 重新获取用户信息
        return { success: true };
      } else {
        return { success: false, error: data.error };
      }
    } catch (error) {
      return { success: false, error: '登录失败' };
    }
  };

  const logout = async () => {
    try {
      await fetch('/api/auth/logout', { method: 'POST' });
      setState({
        user: null,
        permissions: null,
        loading: false,
        error: null
      });
    } catch (error) {
      console.error('登出失败:', error);
    }
  };

  const canEditField = (fieldName: string): boolean => {
    if (!state.permissions) return false;

    // 管理员可以编辑所有字段
    if (state.permissions.canEditAll) return true;

    // 检查具体字段权限
    return state.permissions.editableFields?.includes(fieldName) || false;
  };

  const hasDataSourceAccess = (source: string): boolean => {
    if (!state.permissions) return false;
    return state.permissions.canEditAll || state.permissions.dataSourceAccess.includes(source);
  };

  const isAdmin = (): boolean => {
    return state.user?.role_code === 'A' || false;
  };

  const canManageUsers = (): boolean => {
    return state.permissions?.canManageUsers || false;
  };

  const canManageRoles = (): boolean => {
    return state.permissions?.canManageRoles || false;
  };

  return {
    ...state,
    login,
    logout,
    checkAuth,
    canEditField,
    hasDataSourceAccess,
    isAdmin,
    canManageUsers,
    canManageRoles
  };
}

// 简化版本，只获取基本用户信息
export function useCurrentUser() {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    checkUser();
  }, []);

  const checkUser = async () => {
    try {
      const response = await fetch('/api/auth/me');
      const data = await response.json();

      if (data.success) {
        setUser(data.data.user);
      } else {
        setUser(null);
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      setUser(null);
    } finally {
      setLoading(false);
    }
  };

  return { user, loading, checkUser };
}
